import java.util.Arrays;

public class HashMap {

    public static class Node{
        int val;
        int key;
        Node next;

        public Node(int key,int val){
            this.key=key;
            this.val=val;
        }
    }
    public Node[] array=new Node[10];
    public int usedSize;
    public static final double LOAD_FACTOR=0.75;

    public void put(int key,int val){
        //1.哈希函数找到在数组中的位置
        int index=key%array.length;
        //2.找到这个链表看有没有相同key的元素,如果有更新val
        Node cur=array[index];
        while(cur!=null){
            if(cur.key==key){
                cur.val=val;
            }else{
                cur=cur.next;
            }
        }
        //3.进行头插 (JDK8后都为尾插)
        Node nNode=new Node(key,val);
        nNode.next=array[index];
        array[index]=nNode;
        usedSize++;
        //4.当负载因子超过0.75时扩容
        if(doLoadFunctor()>=LOAD_FACTOR){
            //Arrays.copyOf(array,array.length*2);//直接这样扩容每个元素的hash函数对应的位置可能是错误的 要重新放入
            resize();
        }

    }

    private void resize(){
        Node [] newArray=new Node[array.length*2];
        for (int i = 0; i < array.length; i++) {//每个元素要重新放入新的数组的指定位置
            Node cur=array[i];
            while(cur!=null){
                int newIndex=cur.key%newArray.length;
                Node curN=cur.next;
                cur.next=newArray[newIndex];
                newArray[newIndex]=cur;
                cur=curN;
            }
        }
        array=newArray;
    }
    private double doLoadFunctor(){//计数负载因子
        return  usedSize*1.0f/array.length;
    }

    public int getVal(int key){
        int index=key%array.length;
        Node cur=array[index];
        while(cur!=null){
            if(cur.key==key){
                return cur.val;
            }else {
                cur=cur.next;
            }
        }
        return -1;
    }
}
